package com.nuist.springcaptcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.nuist.springcaptcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private final static long session_valid_timeout = 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/get")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {

        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        // 设置响应返回的类型
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        lineCaptcha.write(response.getOutputStream());
        // 将生成的验证码存储在session中, 方便后续的进行验证码的验证
        session.setAttribute(captchaProperties.getSession().getKey(), lineCaptcha.getCode());
        session.setAttribute(captchaProperties.getSession().getDate(), new Date());
        response.getOutputStream().close();
    }

    @RequestMapping("/check")
    public Boolean checkCaptcha(String inputCode, HttpSession session) {
        if (!StringUtils.hasLength(inputCode)) {
            return false;
        }
        String saveCode = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date saveDate = (Date) session.getAttribute(captchaProperties.getSession().getDate());

        if (inputCode.equalsIgnoreCase(saveCode)) {
            if (saveDate != null && System.currentTimeMillis() - saveDate.getTime() < session_valid_timeout) {
                return true;
            }
        }
        return false;
    }
}
